<template>
  <div class="issues-records-container">
    <h1>问题记录管理</h1>

    <!-- 筛选和搜索工具栏 -->
    <div class="toolbar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
            <el-option label="全部" value="" />
            <el-option label="待处理" value="待处理" />
            <el-option label="处理中" value="处理中" />
            <el-option label="已处理" value="已处理" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filterType" placeholder="问题类型筛选" clearable>
            <el-option label="全部" value="" />
            <el-option label="设施损坏" value="设施损坏" />
            <el-option label="卫生问题" value="卫生问题" />
            <el-option label="安全隐患" value="安全隐患" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filterPriority" placeholder="优先级筛选" clearable>
            <el-option label="全部" value="" />
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKeyword" placeholder="搜索关键词" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 问题列表 -->
    <el-table
      v-loading="loading"
      :data="filteredIssues"
      style="width: 100%; margin-top: 20px"
      @row-click="handleRowClick"
    >
      <el-table-column prop="facilityName" label="设施名称" min-width="120" />
      <el-table-column prop="date" label="报告日期" width="100" sortable />
      <el-table-column prop="reporter_name" label="报告人" width="100" />
      <el-table-column prop="type" label="问题类型" width="100" />
      <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.status === '已处理'
                ? 'success'
                : scope.row.status === '处理中'
                ? 'warning'
                : 'danger'
            "
          >
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.priority === '高'
                ? 'danger'
                : scope.row.priority === '中'
                ? 'warning'
                : 'info'
            "
          >
            {{ scope.row.priority }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click.stop="handleEdit(scope.row)"
          >
            处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredIssues.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 问题详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="问题详情"
      width="50%"
      destroy-on-close
    >
      <el-form
        v-if="currentIssue"
        :model="currentIssue"
        label-width="100px"
        :disabled="isSubmitting"
      >
        <el-form-item label="设施名称">
          <el-input v-model="currentIssue!.facilityName" disabled />
        </el-form-item>
        <el-form-item label="报告日期">
          <el-input v-model="currentIssue!.date" disabled />
        </el-form-item>
        <el-form-item label="报告人">
          <el-input v-model="currentIssue!.reporter_name" disabled />
        </el-form-item>
        <el-form-item label="问题类型">
          <el-input v-model="currentIssue!.type" disabled />
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="currentIssue!.priority">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述">
          <el-input
            v-model="currentIssue!.description"
            type="textarea"
            :rows="4"
            disabled
          />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="currentIssue!.status">
            <el-option label="待处理" value="待处理" />
            <el-option label="处理中" value="处理中" />
            <el-option label="已处理" value="已处理" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员回复">
          <el-input
            v-model="currentIssue!.adminReply"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果或回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveIssue" :loading="isSubmitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

// 定义问题记录接口
interface Issue {
  id: string
  facilityId: string
  facilityName: string
  date: string
  reporter_name: string
  type: string
  description: string
  status: string
  priority: string
  adminReply?: string
}

// 状态变量
const loading = ref(true)
const allIssues = ref<Issue[]>([])
const filterStatus = ref('')
const filterType = ref('')
const filterPriority = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const currentIssue = ref<Issue | null>(null)
const isSubmitting = ref(false)

// 筛选后的问题列表
const filteredIssues = computed(() => {
  let result = allIssues.value

  // 应用筛选条件
  if (filterStatus.value) {
    result = result.filter(issue => issue.status === filterStatus.value)
  }

  if (filterType.value) {
    result = result.filter(issue => issue.type === filterType.value)
  }

  if (filterPriority.value) {
    result = result.filter(issue => issue.priority === filterPriority.value)
  }

  // 应用搜索关键词
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(issue =>
      issue.facilityName.toLowerCase().includes(keyword) ||
      issue.description.toLowerCase().includes(keyword) ||
      issue.reporter_name.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 行点击事件
const handleRowClick = (row: Issue) => {
  currentIssue.value = JSON.parse(JSON.stringify(row)) // 深拷贝
  dialogVisible.value = true
}

// 编辑按钮点击事件
const handleEdit = (row: Issue) => {
  currentIssue.value = JSON.parse(JSON.stringify(row)) // 深拷贝
  dialogVisible.value = true
}

// 保存问题处理结果
const handleSaveIssue = async () => {
  if (!currentIssue.value) return

  isSubmitting.value = true
  try {
    // 创建卫生间设施要素图层
    const bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*']
    })

    // 查询要素
    const query = {
      where: `OBJECTID = ${currentIssue.value.facilityId}`,
      outFields: ['*'],
      returnGeometry: false
    }

    const featureSet = await bathroomLayer.queryFeatures(query)

    if (featureSet.features.length > 0) {
      const feature = featureSet.features[0]
      let issues = []

      try {
        // 解析现有问题列表
        issues = JSON.parse(feature.attributes.issues || '[]')

        // 更新当前问题
        const index = issues.findIndex((issue: any) =>
          issue.date === currentIssue.value?.date &&
          issue.reporter_name === currentIssue.value?.reporter_name &&
          issue.description === currentIssue.value?.description
        )

        if (index !== -1) {
          issues[index] = {
            ...issues[index],
            status: currentIssue.value.status,
            priority: currentIssue.value.priority,
            adminReply: currentIssue.value.adminReply
          }

          // 克隆要素并更新属性
          const updatedFeature = feature.clone()
          updatedFeature.attributes.issues = JSON.stringify(issues)

          // 应用编辑
          const results = await bathroomLayer.applyEdits({
            updateFeatures: [updatedFeature]
          })

          if (results.updateFeatureResults.length > 0) {
            ElMessage.success('问题处理结果已保存')
            dialogVisible.value = false

            // 更新本地列表
            const updatedIssue = {
              ...currentIssue.value,
              status: currentIssue.value.status,
              priority: currentIssue.value.priority,
              adminReply: currentIssue.value.adminReply
            }

            const localIndex = allIssues.value.findIndex(issue =>
              issue.date === updatedIssue.date &&
              issue.reporter_name === updatedIssue.reporter_name &&
              issue.description === updatedIssue.description
            )

            if (localIndex !== -1) {
              allIssues.value[localIndex] = updatedIssue
            }
          } else {
            ElMessage.error('保存失败')
          }
        } else {
          ElMessage.error('未找到对应的问题记录')
        }
      } catch (error) {
        console.error('处理问题记录失败:', error)
        ElMessage.error('处理问题记录失败')
      }
    } else {
      ElMessage.error('未找到对应的设施')
    }
  } catch (error) {
    console.error('保存问题处理结果失败:', error)
    ElMessage.error('保存问题处理结果失败')
  } finally {
    isSubmitting.value = false
  }
}

// 加载所有问题记录
const loadAllIssues = async () => {
  loading.value = true
  try {
    // 创建卫生间设施要素图层
    const bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*']
    })

    // 查询所有设施
    const query = {
      where: '1=1', // 查询所有记录
      outFields: ['*'],
      returnGeometry: false
    }

    const featureSet = await bathroomLayer.queryFeatures(query)

    if (featureSet.features.length > 0) {
      const tempIssues: Issue[] = []

      // 遍历所有设施，提取问题记录
      featureSet.features.forEach(feature => {
        try {
          if (feature.attributes.issues) {
            const issuesList = JSON.parse(feature.attributes.issues || '[]')

            if (issuesList.length > 0) {
              // 为每个问题添加设施信息
              const facilityIssues = issuesList.map((issue: any) => ({
                ...issue,
                facilityId: feature.attributes.OBJECTID,
                facilityName: feature.attributes.name || '未知设施',
                id: `${feature.attributes.OBJECTID}-${issue.date}-${Math.random().toString(36).substring(2, 10)}`
              }))

              tempIssues.push(...facilityIssues)
            }
          }
        } catch (error) {
          console.error('解析设施问题记录失败:', error)
        }
      })

      // 按日期排序（最新的在前）
      allIssues.value = tempIssues.sort((a, b) => {
        return new Date(b.date).getTime() - new Date(a.date).getTime()
      })

      ElMessage.success(`成功加载 ${allIssues.value.length} 条问题记录`)
    } else {
      ElMessage.warning('未找到任何设施记录')
    }
  } catch (error) {
    console.error('加载问题记录失败:', error)
    ElMessage.error('加载问题记录失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取所有问题记录
onMounted(() => {
  loadAllIssues()
})
</script>

<style scoped>
.issues-records-container {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>